<template>
  <div class="submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">提交订单</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">step 01.</div>
            <div class="text">选择购买商品</div>
          </div>
          <div class="item active">
            <div class="number">step 02.</div>
            <div class="text">确认订单信息</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">支付完成订单</div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <div class="submit-box">
          <div class="tit">
            <span class="text">收货地址</span>
          </div>
          <div class="con address-box">
            <div class="item" v-for="(item,index) in addressData" :key="item._id" @click="changeCurrentAddrIndex(index)" :class="{active:currentAddrIndex==index}">
              <div class="name-phone">
                <span class="name">{{item.receiver}}</span>
                <span class="phone">{{item.mobile}}</span>
                <span class="default-tag" v-if="item.isDefault">默认</span>
                <span class="set-default" v-else @click="setDefault(item._id)">设为默认</span>
              </div>
              <div class="address-detail">{{ item.province }}{{ item.city }}{{ item.area }}{{ item.addr }}</div>
              <div class="del-edit">
                <span class="edit" @click="handleEdit(item)"></span>
                <span class="del" @click="handleDelete(item._id)" v-show="!item.isDefault"></span>
              </div>
            </div>
            <div class="item add-address">
              <div class="add-box" @click="handleAdd">
                <div class="img">+</div>
                <div class="text">添加地址</div>
              </div>
            </div>
          </div>
        </div>
        <div class="submit-box">
          <div class="tit">
            <span class="text">支付方式</span>
          </div>
          <div class="con pay-way">
            <div class="item">在线付款</div>
          </div>
        </div>
        <div class="submit-box">
          <div class="tit">
            <span class="text">配送方式</span>
          </div>
          <div class="con pay-way">
            <div class="item">快递配送</div>
          </div>
        </div>
        <div class="submit-box goods-info">
          <div class="tit">
            <span class="text">商品信息</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">&nbsp;</div>
              <div class="info">商品</div>
              <div class="unit-price">单价</div>
              <div class="number">数量</div>
              <div class="total">小计</div>
            </div>
            <div class="msg-con">
              <div>
                <div
                  class="goods-box"
                  v-for="(item, index) in orderInfo"
                  :key="item._id"
                >
                  <div class="img">
                    <a href="/detail" class="img-box">
                      <img
                        :src="
                          item.productId
                            ? item.productId.productImage
                            : item.charProductId.productImage
                        "
                        alt=""
                      />
                    </a>
                  </div>
                  <div class="info">
                    <a href="/detail" class="name">{{
                      item.productId
                        ? item.productId.description
                        : item.charProductId.description
                    }}</a>
                  </div>
                  <div class="unit-price">
                    ￥{{
                      item.productId
                        ? item.productId.price
                        : item.charProductId.price
                    }}
                  </div>
                  <div class="number">
                    ×{{ item.productId ? item.quantity : item.quantity }}
                  </div>
                  <div class="total">￥{{ item.price }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="submit-bottom">
        <div class="statistic-box">
          <div class="item">
            <div class="tit">
              <span class="number">{{ tradeStore.count }}</span
              >件商品，共计：
            </div>
            <div class="con">￥{{ tradeStore.total }}</div>
          </div>
          <div class="item">
            <div class="tit">应付运费：</div>
            <div class="con">
              <p>+￥0.00</p>
            </div>
          </div>
          <div class="item">
            <div class="tit">优惠总额：</div>
            <div class="con">
              <p>-￥0.00</p>
            </div>
          </div>
        </div>
        <div class="detail-box">
          <div class="item">
            <div class="tit">应付总额：</div>
            <div class="con">
              <p>￥{{ tradeStore.total }}</p>
            </div>
          </div>
          <div class="item">
            <span class="text">寄送至：{{choseAddr?.province}} {{choseAddr?.city}} {{choseAddr?.area}} {{choseAddr?.addr}}</span>
            <span class="text"
              >收货人：{{choseAddr?.receiver}}&nbsp;&nbsp;&nbsp;手机号：{{choseAddr?.mobile}}</span
            >
          </div>
        </div>
        <div class="btn-box">
          <a href="javascript:;" class="btn" @click="goPay"
            >提交订单</a
          >
        </div>
      </div>
    </div>
  </div>
  <!-- 收货地址表单 -->
  <el-dialog
    v-model="dialogVisable"
    title="新增收件人信息"
    width="35%"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <el-form :model="form" ref="formRef" :rules="rules">
      <el-form-item prop="receiver" label="收件人：" style="margin-left: 14px">
        <el-input v-model.trim="form.receiver"></el-input>
      </el-form-item>
      <el-form-item prop="mobile" label="手机号码：">
        <el-input v-model="form.mobile"></el-input>
      </el-form-item>
      <el-form-item label="所在地区：">
        <div style="display: flex">
          <el-select
            v-model="form.province"
            @change="handleChange1"
            class="area"
            placeholder="请选择"
            no-data-text="无数据"
          >
            <el-option
              :label="p.name"
              :value="p.code"
              v-for="p in provinceData"
              :key="p._id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="form.city"
            class="area"
            @change="handleChange2"
            placeholder="请选择"
            no-data-text="无数据"
          >
            <el-option
              :label="c.name"
              :value="c.code"
              v-for="c in cityData"
              :key="c._id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="form.area"
            class="area"
            placeholder="请选择"
            no-data-text="无数据"
            ><el-option
              :label="a.name"
              :value="a.code"
              v-for="a in areaData"
              :key="a._id"
            ></el-option
          ></el-select>
        </div>
      </el-form-item>
      <el-form-item prop="addr" label="详细地址：">
        <el-input v-model.trim="form.addr"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisable = false">取消</el-button>
        <el-button type="primary" @click="save">保存收件人信息</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="submit-order">
import { ref, reactive, onMounted, computed } from "vue";
import {
  reqProvinceData,
  reqCityData,
  reqAreaData,
  reqAddressList,
  addAddress,
  updateAddress,
  deleteAddress,
  setDefaultAddr,
} from "@/api/address";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import useUserStore from "@/stores/modules/user";
import useTradeStore from "@/stores/modules/trade";

//获取路由器对象
let $router = useRouter();
let $route = useRoute();

let userStore = useUserStore();
let tradeStore = useTradeStore();

let orderInfo = ref<any>(tradeStore.orderInfo);
let userId = userStore.user._id;
let currentAddrIndex = ref(0)

// 选择的收件人信息
let choseAddr = computed(() => {
  return addressData.value[currentAddrIndex.value]
})

// 地址数据
const addressData = ref<any>([]);
let dialogVisable = ref(false);
// 表单实例
let formRef = ref<any>();

// 地址数据个数
const addressDataLen = computed(() => addressData.value.length);
// 省数据
let provinceData = ref<any>([]);
// 市
let cityData = ref<any>([]);
// 区
let areaData = ref<any>([]);
// 收货地址表单
let form = reactive<any>({
  _id: "",
  receiver: "",
  mobile: "",
  province: "",
  city: "",
  area: "",
  addr: "",
  isDefault: false,
});

// 点击提交订单按钮的回调
const goPay =async () => {
  let totalPrice = 0
  let items = orderInfo.value.map((item:any) => ({
    productId:item.productId ? item.productId._id : null,
    charProductId:item.charProductId ? item.charProductId._id : null,
    quantity:item.quantity,
    price:item.price
  }))
  items.forEach((item:any)=> {
    totalPrice += Number(item.price)
  });
  let data = {userName:userStore.user.userName,items,totalPrice,userAddr:addressData.value[currentAddrIndex.value]}
  await tradeStore.handleSubmitOrder(data)
  $router.push('/pay')
}

// 点击地址修改索引
const changeCurrentAddrIndex = (index:number) => {
  currentAddrIndex.value = index
}

// 新增收货地址回调
const handleAdd = () => {
  if (addressDataLen.value >= 6) {
    ElMessage.warning("最多可创建6个收货地址!");
    return;
  }
  dialogVisable.value = true;
  reset();
};

// 点击修改按钮
const handleEdit = (addr: any) => {
  dialogVisable.value = true;
  Object.assign(form, JSON.parse(JSON.stringify(addr)));
};

// 点击删除按钮的回调
const handleDelete = async (_id: any) => {
  let result = await deleteAddress(_id);
  if (result.code == 200) {
    ElMessage.success(result.msg);
    currentAddrIndex.value = 0
    getAddressInfo();
  } else {
    ElMessage.error(result.msg);
  }
};

// 点击保存按钮的回调
const save = async () => {
  await formRef.value.validate();
  if (!form.province || !form.city || !form.area) {
    ElMessage.warning("请输入完整地区信息！");
    return;
  }
  // 新增
  if (!form._id) {
    let data = Object.assign(form, { userId });
    let result = await addAddress(data);
    if (result.code == 200) {
      dialogVisable.value = false;
      ElMessage.success(result.msg);
      currentAddrIndex.value = 0
      getAddressInfo();
    } else {
      ElMessage.error(result.msg);
    }
  } else {
    // 修改
    let result = await updateAddress(form);
    if (result.code == 200) {
      dialogVisable.value = false;
      ElMessage.success(result.msg);
      currentAddrIndex.value = 0
      getAddressInfo();
    } else {
      ElMessage.error(result.msg);
    }
  }
};

// 设置默认地址
const setDefault = async (id: any) => {
  let result = await setDefaultAddr({ userId, _id: id });
  if (result.code == 200) {
    ElMessage.success(result.msg);
    currentAddrIndex.value = 0
    getAddressInfo();
  } else {
    ElMessage.error(result.msg);
  }
};

const reset = () => {
  Object.assign(form, {
    _id: "",
    receiver: "",
    mobile: "",
    province: "",
    city: "",
    area: "",
    addr: "",
    isDefault: false,
  });
};

const handleChange1 = () => {
  form.city = "";
  form.area = "";
  getCityData();
};

const handleChange2 = () => {
  form.area = "";
  getAreaData();
};
// 获取地址列表
const getAddressInfo = async () => {
  let result = await reqAddressList(userId);
  if (result.code == 200) {
    addressData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};
// 获取省数据
const getProvinceData = async () => {
  let result = await reqProvinceData();
  if (result.code == 200) {
    provinceData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 获取市数据
const getCityData = async () => {
  let result = await reqCityData(form.province);
  if (result.code == 200) {
    cityData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 获取区数据
const getAreaData = async () => {
  let result = await reqAreaData(form.city);
  if (result.code == 200) {
    areaData.value = result.data;
  } else {
    ElMessage.error(result.msg);
  }
};

// 手机号
const validatePhone = (rule: any, value: any, callback: any) => {
  if (!/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error("请输入正确的手机号"));
  } else {
    callback();
  }
};
// 详细地址
const validateAddr = (rule: any, value: any, callback: any) => {
  if (!value && value.length < 5) {
    callback(new Error("详细地址不能少于5个字"));
  } else {
    callback();
  }
};
// 收件人
const validateReceiver = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请输入收件人"));
  } else {
    callback();
  }
};
// 校验规则
const rules = {
  receiver: [{ validator: validateReceiver, trigger: "blur" }],
  mobile: [{ validator: validatePhone, trigger: "blur" }],
  addr: [{ validator: validateAddr, trigger: "blur" }],
};

onMounted(() => {
  getAddressInfo();
  getProvinceData();
});
</script>

<style lang="scss" scoped>
.submit-order {
  min-height: 535px;
  padding-bottom: 40px;
  background-color: #f8f8f8;
  .content {
    width: 1200px;
    margin: auto;
    .step-box {
      display: flex;
      height: 70px;
      padding: 0 20px 7px;
      box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.05);
      margin-bottom: 30px;
      border-bottom: 2px solid #4caf50;
      .left {
        flex: 1;
        margin-top: 16px;
        .img {
          background: url(../../assets/icons.d354c61.png) no-repeat -43px -249px;
          display: inline-block;
          vertical-align: top;
          height: 38px;
          width: 38px;
        }
        .text {
          display: inline-block;
          vertical-align: top;
          height: 38px;
          line-height: 38px;
          font-size: 15px;
          font-weight: 600;
        }
      }
      .steps {
        display: flex;
        .item {
          padding-left: 90px;
          margin-left: 40px;
          position: relative;
          background: url(../../assets/icons.d354c61.png) no-repeat 0 -292px;
          .number {
            height: 20px;
            line-height: 20px;
            margin-top: 12px;
            color: #999;
            font-family: math;
          }
          .text {
            height: 24px;
            line-height: 24px;
            font-size: 14px;
            color: #999;
          }
        }
        .item:first-child {
          background: none;
        }
        .active {
          .number {
            color: #000;
          }
          .text {
            color: #000;
          }
        }
      }
    }
    .submit-con {
      .submit-box {
        font-size: 12px;
        margin-top: 20px;
        padding-bottom: 30px;
        border-bottom: 1px solid #eee;
        &:last-child {
          border: 0;
        }
        .tit {
          padding: 10px 0;
          display: flex;
          height: 14px;
          line-height: 14px;
          .text {
            font-size: 14px;
            font-weight: 600;
          }
        }
        .con {
          display: flex;
          flex-wrap: wrap;
          position: relative;
        }
        .address-box {
          .item {
            padding: 20px 15px;
            width: 242px;
            min-height: 75px;
            border: 1px solid #eee;
            margin-left: 20px;
            margin-top: 20px;
            transition: all 0.2s;
            cursor: pointer;
            position: relative;
            box-sizing: content-box;
            .name-phone {
              margin: 5px 0 10px;
              display: flex;
              align-items: center;
              .name {
                max-width: 100px;
                white-space: nowrap;
                text-overflow: ellipsis;
                overflow: hidden;
              }
              .phone {
                margin-left: 10px;
                font-family: arial;
              }
              .default-tag {
                display: inline-block;
                background: #e1251b;
                color: #fff;
                padding: 0 3px;
                border-radius: 2px;
                font-size: 10px;
                margin-left: 10px;
              }
              .set-default {
                color: #005ea7;
                vertical-align: top;
                transition: all 0.2s;
                margin-left: 10px;
                display: none;
                &:hover {
                  color: #e1251b;
                }
              }
            }
            .address-detail {
              color: #999;
              line-height: 20px;
            }
            .del-edit {
              position: absolute;
              bottom: 10px;
              right: 15px;
              display: none;
              .edit {
                display: inline-block;
                width: 14px;
                height: 14px;
                background: url(../../assets/icons.d354c61.png) no-repeat;
                background-position: 0 -434px;
                cursor: pointer;
                &:hover {
                  background-position: -19px -434px;
                }
              }
              .del {
                display: inline-block;
                margin-left: 5px;
                width: 14px;
                height: 14px;
                background: url(../../assets/icons.d354c61.png) no-repeat;
                background-position: 0 -415px;
                cursor: pointer;
                &:hover {
                  background-position: -19px -415px;
                }
              }
            }
          }
          .active {
            border-color: #e1251b;
          }
          .item:hover {
            border-color: #e1251b;
            .set-default{
              display: inline-block;
            }
            .del-edit {
              display: block;
            }
          }
          .item:nth-child(4n-3) {
            margin-left: 0;
          }
        }
        .add-address {
          padding: 20px 15px;
          width: 242px;
          min-height: 75px;
          border: 1px solid #eee;
          margin-left: 20px;
          margin-top: 20px;
          transition: all 0.2s;
          cursor: pointer;
          position: relative;
          &:hover {
            border-color: #ddd !important;
            .img {
              background: #e1251b !important;
              color: #fff;
            }
            .text {
              color: #e1251b;
            }
          }
          .add-box {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: #999;
            .img {
              width: 30px;
              height: 30px;
              font-family: arial;
              background: #efefef;
              display: flex;
              justify-content: center;
              align-items: center;
              font-size: 22px;
              border-radius: 50%;
              margin: auto auto 7px;
              transition: all 0.2s;
            }
            .text {
              transition: all 0.2s;
            }
          }
        }
        .pay-way {
          .item {
            padding: 8px 30px;
            border: 1px solid #eee;
            margin-left: 0;
            margin-top: 20px;
            transition: all 0.2s;
            cursor: pointer;
            position: relative;
            border-color: #e1251b;
          }
        }
        .goods-msg {
          margin-top: 20px;
          .msg-tab {
            padding: 10px;
            border: 1px solid #eee;
            background: #f9f9f9;
            display: flex;
            .img {
              padding: 0 10px 0 20px;
              width: 80px;
              box-sizing: content-box;
            }
            .info {
              width: 450px;
            }
            .unit-price {
              width: 220px;
              text-align: center;
            }
            .number {
              width: 220px;
              text-align: center;
            }
            .total {
              width: 220px;
              text-align: center;
            }
          }
          .msg-con {
            background: #f9f9f9;
            padding-bottom: 25px;
            margin-top: 15px;
            .goods-box {
              padding: 15px 0;
              display: flex;
              align-items: center;
              position: relative;
              &::after {
                position: absolute;
                bottom: 0;
                left: 20px;
                right: 20px;
                display: block;
                width: auto;
                height: 1px;
                background: #eee;
                content: " ";
              }
              .img {
                padding: 0 10px 0 20px;
                width: 80px;
                .img-box {
                  display: block;
                  width: 80px;
                  height: 80px;
                  font-size: 0;
                  img {
                    width: 100%;
                    height: 100%;
                  }
                }
              }
              .info {
                line-height: 20px;
                align-self: flex-start;
                width: 450px;
                .name {
                  max-width: 380px;
                  max-height: 36px;
                  line-height: 18px;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  display: -webkit-box;
                  text-decoration: none;
                  color: #000;
                  &:hover {
                    color: #e1251b;
                    text-decoration: none;
                  }
                }
              }
              .unit-price {
                font-family: verdana;
                width: 220px;
                text-align: center;
              }
              .number {
                font-family: verdana;
                width: 220px;
                text-align: center;
              }
              .total {
                font-family: verdana;
                font-weight: 600;
                color: #e1251b;
                width: 220px;
                text-align: center;
              }
            }
          }
        }
      }
    }
    .submit-bottom {
      font-size: 12px;
      .statistic-box {
        margin-top: 30px;
        margin-bottom: 20px;
        .item {
          display: flex;
          justify-content: flex-end;
          min-height: 24px;
          line-height: 24px;
          margin-bottom: 5px;
          .tit {
            display: flex;
            justify-content: flex-end;
            width: 180px;
            margin-right: 20px;
            text-align: right;
            .number {
              color: #e1251b;
              margin-right: 3px;
            }
          }
          .con {
            min-width: 125px;
            text-align: right;
            margin-right: 20px;
            font-family: verdana;
          }
        }
      }
      .detail-box {
        padding: 15px 0;
        line-height: 20px;
        text-align: right;
        border-top: 1px solid #eee;
        color: #999;
        background-color: #f9f9f9;
        margin-left: 20px;
        .item {
          display: flex;
          justify-content: flex-end;
          line-height: 25px;
          .tit {
            width: 180px;
            margin-right: 20px;
            text-align: right;
            color: #000;
          }
          .con {
            min-width: 125px;
            text-align: right;
            margin-right: 20px;
            font-family: verdana;
            color: #e1251b;
            font-size: 18px;
            font-weight: 600;
          }
          .text {
            margin-right: 20px;
          }
        }
      }
      .btn-box {
        display: flex;
        justify-content: flex-end;
        .btn {
          display: block;
          width: 135px;
          height: 38px;
          line-height: 38px;
          text-align: center;
          background: #e1251b;
          color: #fff;
          margin: 20px 20px 0 0;
          font-size: 15px;
          font-weight: 600;
          border-radius: 2px;
          text-decoration: none;
          &:hover {
            opacity: 0.8;
          }
        }
      }
    }
  }
}
.area {
    display: inline-block;
    height: 20px;
    line-height: 20px;
    width: 125px;
    margin-right: 10px;
    position: relative;
  }
</style>
